package cn.geminis.fabric.service.controller;

import cn.geminis.fabric.service.service.ChaincodeService;
import lombok.RequiredArgsConstructor;
import org.hyperledger.fabric.gateway.Gateway;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;

/**
 * @author puddi
 */
@RestController
@RequestMapping("/chaincode")
@RequiredArgsConstructor
public class ChaincodeController {

    private final Gateway gateway;
    private final ChaincodeService chaincodeService;

    @PutMapping("/{channel}/{chaincode}/{id}")
    public void set(@PathVariable String channel,
                    @PathVariable String chaincode,
                    @PathVariable String id,
                    @RequestBody String value) throws Exception {
        var network = gateway.getNetwork(channel);
        var contract = network.getContract(chaincode);
        contract.submitTransaction("set", id, value);
    }

    @GetMapping("/{channel}/{chaincode}/{id}")
    public String get(@PathVariable String channel,
                      @PathVariable String chaincode,
                      @PathVariable String id) throws Exception {
        return chaincodeService.get(channel, chaincode, id);
    }

    @DeleteMapping("/{channel}/{chaincode}/{id}")
    public void delete(@PathVariable String channel,
                       @PathVariable String chaincode,
                       @PathVariable String id) throws Exception {
        var network = gateway.getNetwork(channel);
        var contract = network.getContract(chaincode);
        contract.submitTransaction("delete", id);
    }
}
